package com.withoutwords.engine.social;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.withoutwords.R;

import com.withoutwords.engine.GameController;
import com.withoutwords.engine.MyInfo;
import com.withoutwords.engine.social.listeners.ICurrentUserInfoListener;
import com.withoutwords.engine.social.listeners.ILoginListener;
import com.withoutwords.engine.social.listeners.ISocialFriendListListener;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class FacebookController implements ISocialNetworkController {
	final String APP_ID = "190851861041135";//190851861041135
	/*final String Share_URL = "www.faye2.com/bdonkalam/fb_share"; 
	final String titleCode = "ttttttttttttttttt";
	final String descriptionCode = "dddddddddddddddddddd";
	
	final String Share_Open_Graph = "<head prefix=\"og: http://ogp.me/ns fb: http://ogp.me/ns/fb\">"+
   "<meta property=\"fb:app_id\"       content=\""+APP_ID+"\" />" +
   "<meta property=\"og:type\"         content=\"game\" />" +
   "<meta property=\"og:url\"          content=\""+ Share_URL +"\" /> " +
   "<meta property=\"og:title\"        content=\""+titleCode+"\" />  "+
   "<meta property=\"og:description\"  content=\""+descriptionCode+"\" />" +
   "<meta property=\"og:image\"        content=\""+ Share_URL +"/game.png\" />" +
   "<meta property=\"og:video\"        content=\""+ Share_URL +"/game.swf\" />" +
   "<meta property=\"og:video:width\"  content=\"398\" />" + 
   "<meta property=\"og:video:height\" content=\"299\" /> "+
   "<meta property=\"og:video:type\"   content=\"application/x-shockwave-flash\" />" ;*/
	 
	 Facebook facebook = new Facebook(APP_ID);
	 AsyncFacebookRunner fbRunner = new AsyncFacebookRunner(facebook);
	 private SharedPreferences mPrefs;
	
	 String userEmail;
	 String userFB_id;
	//request login to social network
		public void requestLogin(final Activity Act,final ILoginListener l)
		{
			if(!isLoggenIn(Act)) {

	            facebook.authorize(Act, new String[] {}, new DialogListener() {
	                @Override
	                public void onComplete(Bundle values) {
	                	
	                    SharedPreferences.Editor editor = mPrefs.edit();
	                    editor.putString("access_token", facebook.getAccessToken());
	                    editor.putLong("access_expires", facebook.getAccessExpires());
	                    editor.commit();
	                    l.onLoginSuccess();
	                   // Intent newIntent = new Intent( Act,Act.getComponentName());
	                   // Act.
	                    //newIntent.putExtra(Common.fbLoginSuccess, 1);
	                    //Act.Intent(newIntent);
	                }
	    
	                @Override
	                public void onFacebookError(FacebookError error) {
	                	Log.e("FacebookController", "Error : "+ error.getMessage());
	                	l.onError(error.getMessage());
	                }
	    
	                @Override
	                public void onError(DialogError e) {
	                	 l.onError(e.getMessage());
	                }
	    
	                @Override
	                public void onCancel() {
	                	 l.onError("Cancel");
	                }
	            });
	        }
		}
		
		//callback for login request
		public boolean onLoginCallback(int requestCode,int resultCode,Intent data)
		{
			
			facebook.authorizeCallback(requestCode, resultCode, data);
			if(data != null)
			{
			 String error = data.getStringExtra("error");
			 return (error == null) ;
			}
			return true;
            
		}
		
		//share data on social network
	/*	public void share(Context context,String sharedata)
		{
			/*NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
				  kAppId, @"app_id",
				  @"https://developers.facebook.com/docs/reference/dialogs/", @"link",
				  @"http://fbrell.com/f8.jpg", @"picture",
				  @"Facebook Dialogs", @"name",
				  @"Reference Documentation", @"caption",
				  @"Using Dialogs to interact with users.", @"description",
				  nil];
			
			Bundle params = new Bundle();
		    params.putString("description", sharedata);
		    params.putString("caption", "My Caption");
          //  params.putString("description", getString(R.string.app_desc));
           // params.putString("picture", Utility.HACK_ICON_URL);
            params.putString("name", "My Name");
            params.putString("link", Share_URL);
			 facebook.dialog(context, "feed",params,new DialogListener() {
	                @Override
	                public void onComplete(Bundle values) {
	                  
	                }
	    
	                @Override
	                public void onFacebookError(FacebookError error) {}
	    
	                @Override
	                public void onError(DialogError e) {}
	    
	                @Override
	                public void onCancel() {}
	            });
		}*/
		
		public void inviteFriends(Context context,String invitationString)
        {
            Bundle params = new Bundle();
            params.putString("message", invitationString);
            params.putString("to", "");
             facebook.dialog(context, "apprequests",params,new DialogListener() {
                    @Override
                    public void onComplete(Bundle values) {
                        Log.e("app request complete", "success");
                      
                    }
        
                    @Override
                    public void onFacebookError(FacebookError error) {
                        Log.e("app request complete", "FacebookError");
                    }
        
                    @Override
                    public void onError(DialogError e) {
                        Log.e("app request complete", "DialogError");
                    }
        
                    @Override
                    public void onCancel() {
                        Log.e("app request complete", "onCancel");
                    }
                });
        }

		public void share(final Context context,final String sharedata,byte[] bdata)
		{ 
			//Bitmap icon = mBitmap;
			Intent share = new Intent(Intent.ACTION_SEND);
			share.setType("image/jpeg");
			//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			//icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
			String FilePath = Environment.getExternalStorageDirectory() + File.separator + "drawing.jpg";
			File f = new File(FilePath);
			try {
			    f.createNewFile();
			    FileOutputStream fo = new FileOutputStream(f);
			    fo.write(bdata);
			} catch (IOException e) {                       
			        e.printStackTrace();
			}
			share.putExtra(Intent.EXTRA_TEXT, "I am playing Act n' Guess with " + GameController.getInstance().getCurrentGame().getGameOwner().Name );
			share.putExtra(Intent.EXTRA_SUBJECT, "Act n' Guess" );
			share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
			context.startActivity(Intent.createChooser(share, "Share Image"));
			
				/*	Bundle params = new Bundle();
	            params.putString("method", "photos.upload");
	            params.putByteArray("picture", bdata);

	            AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
	            mAsyncRunner.request(null, params, "POST", new RequestListener() {
					
					@Override
					public void onMalformedURLException(MalformedURLException e, Object state) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onIOException(IOException e, Object state) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onFileNotFoundException(FileNotFoundException e, Object state) {
						// TODO Auto-generated method stub
						
					}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(final String response, Object state) {
				
							
			
			}
		},null);
		*/				
					
        }

public void share(Context context,String sharedata)
        {
            Bundle params = new Bundle();
            params.putString("app_id", APP_ID);
            params.putString("name", context.getResources().getString(R.string.app_name));
            params.putString("description", sharedata);
            params.putString("picture", "http://www.faye2.com/bdonkalam/fb_share/intro.png");            
             facebook.dialog(context, "feed",params,new DialogListener() {
                    @Override
                    public void onComplete(Bundle values) {
                      
                    }
        
                    @Override
                    public void onFacebookError(FacebookError error) {}
        
                    @Override
                    public void onError(DialogError e) {}
        
                    @Override
                    public void onCancel() {}
                });
        }
		
		private ArrayList<SocialUser> parseJsonFriendList(String jsonResponse)
		{
			ArrayList<SocialUser> friendsArray = new ArrayList<SocialUser>();
			try {
				JSONObject response = new JSONObject(jsonResponse);
				JSONArray jsonFriendList = response.getJSONArray("data");
				
				for(int i=0 ;i < jsonFriendList.length() ; i++)
				{
					JSONObject jObj = jsonFriendList.getJSONObject(i);
					SocialUser sf = new SocialUser();
					sf.network = SocialNetwork.Facebook;
					sf.SocialID = jObj.getString("id");
					sf.Name = jObj.getString("name");
					friendsArray.add(sf);
				}
				
				
				//return friendsArray;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
			return friendsArray;
		}
		//read friends
		public ArrayList<SocialUser> readFriendList(boolean bGameUsersOnly)
		{
			//return null;
			try {
				String jsonFriends = facebook.request("me/friends");
				return parseJsonFriendList(jsonFriends);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		public void readFriendList(final ISocialFriendListListener listener,boolean bGameUsersOnly) {
		fbRunner.request("me/friends", new RequestListener() {
			
			@Override
			public void onMalformedURLException(MalformedURLException e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onIOException(IOException e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onFileNotFoundException(FileNotFoundException e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onFacebookError(FacebookError e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onComplete(String response, Object state) {
				// TODO Auto-generated method stub
				if(!response.contains("OAuthException"))
				{
				listener.onFriendListRecieved(parseJsonFriendList(response));
				}
				else
				{
					listener.onError("OAuthException");
			//	facebook.isSessionValid();
				}
			}
		});
			
		}
		
		public boolean isLoggenIn(Activity Act)
		{
			/*
	         * Get existing access_token if any
	         */
			//Context context ;
			mPrefs = Act.getApplication().getSharedPreferences("Facebook", Activity.MODE_PRIVATE);
	     //   mPrefs = Act.getPreferences(Activity.MODE_PRIVATE);
	        String access_token = mPrefs.getString("access_token", null);
	        long expires = mPrefs.getLong("access_expires", 0);
	        if(access_token != null) {
	            facebook.setAccessToken(access_token);
	            facebook.extendAccessTokenIfNeeded(Act, null);
	        }
	        if(expires != 0) {
	            facebook.setAccessExpires(expires);
	        }
	        
	        /*
	         * Only call authorize if the access_token has expired.
	         */
	        return facebook.isSessionValid();
		}

		@Override
		public void getCurrentUserInfo(final ICurrentUserInfoListener listener) {
			fbRunner.request("me", new RequestListener() {
				
				@Override
				public void onMalformedURLException(MalformedURLException e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onIOException(IOException e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onFileNotFoundException(FileNotFoundException e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onFacebookError(FacebookError e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onComplete(String jsonResponse, Object state) {
					// TODO Auto-generated method stub
					MyInfo me = new MyInfo();
					try {
					JSONObject jObj = new JSONObject(jsonResponse);
						SocialUser sf = new SocialUser();
						sf.network = SocialNetwork.Facebook;
						sf.SocialID = jObj.getString("id");
						sf.Name = jObj.getString("name");
							
						me.setSocialUser(sf);
						me.setEmail(jObj.getString("email"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						
					}
					listener.onCurrentUserInfoRecieved(me);
				}
			});
			
		}

		@Override
		public void logout(Context context) {
			try {
				facebook.logout(context);
				mPrefs = context.getApplicationContext().getSharedPreferences("Facebook", Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = mPrefs.edit();
                editor.putString("access_token", null);
                editor.putLong("access_expires", 0);
                editor.commit();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

		

		
		

}
